<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        #box {
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: yellow;
            /*opacity: 0;*/
        }
    </style>
</head>

<body>
    <button id="btn">let's go</button>
    <div id="box"></div>
    <script>
    var box = document.getElementById("box");
    var btn = document.getElementById("btn");

    //var timer = null;
    btn.onclick = function () {
        animate(box, {"height": 200}, function () {
            //alert("动画执行完了");
            animate(box, {"height": 20}, function () {
                animate(box, {"opacity": 0.3})
            })
        });
    }

    //需求 将 任意对象 的 任意属性 渐渐地变为 目标值
    function animate(obj, json, fn) {
        clearInterval(obj.timer);
        obj.timer = setInterval(function () {
            var flag = true;
            for (var k in json) {
                if (k == "opacity") {
                    var leader = getStyle(obj, k) * 100;
                    var target = json[k] * 100;
                    var step = (target - leader) / 10;
                    step = step > 0 ? Math.ceil(step) : Math.floor(step);
                    leader = leader + step;
                    obj.style[k] = leader / 100;
                } else if (k == "zIndex") {
                    obj.style[k] = json[k];
                } else {
                    var leader = parseInt(getStyle(obj, k)) || 0;
                    var target = json[k];
                    var step = (target - leader) / 10;
                    step = step > 0 ? Math.ceil(step) : Math.floor(step);
                    leader = leader + step;
                    obj.style[k] = leader + "px";
                }
                console.log("target: " + target + "leader: " + leader + "step: " + step);
                if (leader != target) {
                    flag = false;//告诉人家 我还有没到的呢
                }
            }
            //最后再判断 如果标记仍然是true说明 没有没到达的了
            if (flag) {
                clearInterval(obj.timer);
                if (fn) {
                    fn();
                }
            }
        }, 15)
    }

    function getStyle(obj, attr) {
        if (obj.currentStyle) {
            return obj.currentStyle[attr];
        } else {
            return window.getComputedStyle(obj, null)[attr];
        }
    }

</script>
</body>

</html>